<?php
/**
 * 后台banner管理接口
 * Author: Zeon
 * Date: 2018/1/23
 * Created by Panxsoft.
 */
namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Http\Models\HomepageBanner;
use App\Http\Requests\Admin\HomepageBannerStoreRequest;
use App\Http\Requests\Admin\HomepageBannerUpdateRequest;
use App\Services\Utils\ApiChecker;
use App\Services\Utils\ApiResponser;
use Illuminate\Http\Request;
use Illuminate\Http\Response;

class HomepageBannerController extends Controller
{
    use ApiResponser,
        ApiChecker;

    /**
     * @return array
     */
    public function index()
    {
        $banners = (new HomepageBanner)
            ->latest('priority')
            ->latest()
            ->get();

        return $this->response(compact('banners'));
    }

    /**
     * @param HomepageBannerStoreRequest $request
     * @return \Illuminate\Contracts\Routing\ResponseFactory|\Symfony\Component\HttpFoundation\Response
     */
    public function store(HomepageBannerStoreRequest $request)
    {
        (new HomepageBanner)->create($request->only('image', 'priority'));

        return $this->responseCreated();
    }

    /**
     * @param HomepageBannerUpdateRequest $request
     * @param $id
     * @return \Illuminate\Contracts\Routing\ResponseFactory|\Symfony\Component\HttpFoundation\Response
     * @throws \App\Exceptions\AdminManageException
     */
    public function update(HomepageBannerUpdateRequest $request, $id)
    {
        /** @var HomepageBanner $banner */
        $banner = (new HomepageBanner)->find($id);
            $this->checkItemExist($banner, 'banner');

        $banner->update($request->only('image', 'priority'));

        return $this->responseAccepted();
    }

    /**
     * @param $id
     * @return \Illuminate\Contracts\Routing\ResponseFactory|\Symfony\Component\HttpFoundation\Response
     * @throws \App\Exceptions\AdminManageException
     * @throws \Exception
     */
    public function destroy($id)
    {
        /** @var HomepageBanner $banner */
        $banner = (new HomepageBanner)->find($id);
            $this->checkItemExist($banner, 'banner');

        $banner->delete();

        return $this->responseAccepted();
    }
}
